package com.yuanli.cosmeticmirror.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatCheckBox;

import com.comenjoysoft.baselibrary.util.EncryptUtils;
import com.comenjoysoft.baselibrary.util.SPUtils;
import com.mob.MobSDK;
import com.orhanobut.logger.Logger;
import com.rxjava.rxlife.RxLife;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yuanli.cosmeticmirror.R;
import com.yuanli.cosmeticmirror.base.BaseActivity;
import com.yuanli.cosmeticmirror.base.Constant;
import com.yuanli.cosmeticmirror.base.MyApp;
import com.yuanli.cosmeticmirror.bean.LoginBean;
import com.yuanli.cosmeticmirror.model.iview.ILoginView;
import com.yuanli.cosmeticmirror.persenter.LoginPersenter;
import com.yuanli.cosmeticmirror.utils.GeneralUtils;
import com.yuanli.cosmeticmirror.utils.PhoneUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

import static com.yuanli.cosmeticmirror.base.Constant.USER_AGREEMENT_PRIVACY_POLICY;

public class LoginActivity extends BaseActivity implements ILoginView {
    @BindView(R.id.login_head)
    ImageView loginHead;
    @BindView(R.id.login_account)
    EditText loginAccount;
    @BindView(R.id.login_password)
    EditText loginPassword;
    @BindView(R.id.login_cb)
    AppCompatCheckBox loginCb;
    @BindView(R.id.login_enter)
    TextView loginEnter;
    @BindView(R.id.login_enter_phone)
    TextView loginEnterPhone;
    @BindView(R.id.find_password)
    TextView findPassword;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.login_protocol)
    TextView loginProtocol;
    @BindView(R.id.login_wechat)
    ImageView loginWechat;
    @BindView(R.id.login_qq)
    ImageView loginQq;
    @BindView(R.id.login_sina)
    ImageView loginSina;
    private LoginPersenter persenter;
    private Platform platform;
    private long mLastClickTime = 0;
    public final long TIME_INTERVAL = 1000L;
    private boolean isOther = false;

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void init(Bundle bundle) {
        persenter = new LoginPersenter(this, this);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        String userName = getIntent().getStringExtra("userName");
        if (!TextUtils.isEmpty(userName)) {
            loginAccount.setText(userName);
        }
    }

    @Override
    protected void destroy() {

    }

    private boolean mIsOtherLogin;


    @OnClick({R.id.login_enter,
            R.id.login_enter_phone,
            R.id.login_protocol,
            R.id.login_private,
            R.id.find_password,
            R.id.register,
            R.id.login_wechat,
            R.id.login_qq,
            R.id.login_sina})
    public void onViewClicked(View view) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickTime < TIME_INTERVAL) {
            // do something
            return;
        }
        mIsOtherLogin = false;
        mLastClickTime = nowTime;
        switch (view.getId()) {
            case R.id.login_enter:
                String phone = loginAccount.getText().toString();
                String password = loginPassword.getText().toString();
                if (!loginCb.isChecked()) {
                    showToast("请先阅读并同意该协议后再进行登录");
                    return;
                }
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(password)) {
                    showToast("账号或密码未填写");
                    return;
                }
                showLoadDialog("正在登录...");
                password = EncryptUtils.encryptMD5ToString(password).toUpperCase();
                persenter.login(phone, password);
                isOther = false;
                break;

            case R.id.login_enter_phone:
                if (!loginCb.isChecked()) {
                    showToast("请先阅读并同意该协议后再进行登录");
                    return;
                }
                showLoadDialog();
                getPhone();
                break;
            case R.id.find_password:
                startActivity(new Intent(LoginActivity.this, FindPwdActivity.class));
                break;
            case R.id.register:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.login_wechat:
                if (!loginCb.isChecked()) {
                    showToast("请先阅读并同意该协议后再进行登录");
                    return;
                }
                isOther = true;
                mIsOtherLogin = true;
                persenter.otherLogin(Wechat.NAME);
                break;
            case R.id.login_qq:
                //                MobSDK.submitPolicyGrantResult(loginCb.isChecked(), null);
                if (!loginCb.isChecked()) {
                    showToast("请先阅读并同意该协议后再进行登录");
                    return;
                }
                isOther = true;
                mIsOtherLogin = true;
                persenter.otherLogin(QQ.NAME);
                break;
            case R.id.login_sina:
                showToast("暂不支持微博登录");
                break;
            case R.id.login_protocol:
                startActivity(new Intent(LoginActivity.this, ProtocolActivity.class).putExtra(USER_AGREEMENT_PRIVACY_POLICY, 1));
                break;
            case R.id.login_private:
                startActivity(new Intent(LoginActivity.this, ProtocolActivity.class).putExtra(USER_AGREEMENT_PRIVACY_POLICY, 2));
                break;
            default:
                break;
        }
    }

    private void getPhone() {
        new RxPermissions(this)
                .request(Manifest.permission.READ_PHONE_STATE)
                .subscribeOn(Schedulers.io())
                .as(RxLife.asOnMain(this))
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        PhoneUtils phoneUtils = new PhoneUtils(LoginActivity.this);
                        String phone1 = phoneUtils.getPhone();
                        if (TextUtils.isEmpty(phone1)) {
                            dialogDismiss();
                            showToast("获取号码失败，请输入手机号码进行登录");
                            return;
                        }
                        persenter.register("", phone1, GeneralUtils.getRandom(6));
                    } else {
                        dialogDismiss();
                        showToast("请求权限失败");
                    }
                });
    }

    @Override
    public void loginSucess(LoginBean object) {
        dialogDismiss();
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }

    @Override
    public void error() {
        dialogDismiss();
        if (isOther) {
            if (platform != null) {
                if (!TextUtils.isEmpty(platform.getDb().getUserId())) {
                    showLoadDialog();
                    persenter.register(platform.getDb().getUserName(), platform.getDb().getUserId(), "123456");
                    return;
                }
            }
        }
        if (mIsOtherLogin){
            showToast("登录失败");
        }else{
            showToast("登录失败,请尝试第三方登录");
        }
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void otherLoginSucess(Platform platform) {
        this.platform = platform;
        showLoadDialog();
        String password = EncryptUtils.encryptMD5ToString("123456").toUpperCase();
        persenter.login(platform.getDb().getUserId(), password);
    }

    @Override
    public void otherLoginError() {
        dialogDismiss();
        showToast("第三方登录失败");
        Logger.e("otherLoginError");
    }

    @Override
    public void register() {
        dialogDismiss();
        MyApp.isLogin = true;
        if (platform != null) {
            SPUtils.getInstance().put(Constant.SP_USER_NAME, platform.getDb().getUserName());
            SPUtils.getInstance().put(Constant.SP_USER_PHOTO_NET, platform.getDb().getUserIcon());
        }
        String password = EncryptUtils.encryptMD5ToString("123456").toUpperCase();
        SPUtils.getInstance().put(Constant.SP_USER_PASSWORD, password);
        SPUtils.getInstance().put(Constant.IS_FIRST_LOGIN, true);
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }
}
